package com.ssm.controllor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;

@Controller
public class PoiController {

	// storeName是文件名

	@RequestMapping("/devPdf")
	@ResponseBody
	public void devPdf(HttpServletRequest request, HttpServletResponse response, String storeName) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		String downLoadPath = ctxPath + "/file/" + storeName;
		response.setContentType("application/pdf");
		FileInputStream in = new FileInputStream(new File(downLoadPath));
		OutputStream out = response.getOutputStream();
		byte[] b = new byte[512];
		while ((in.read(b)) != -1) {
			out.write(b);
		}
		out.flush();
		in.close();
		out.close();
	}
	@RequestMapping("/devWord")
	@ResponseBody
	public void devWord(HttpServletRequest request, HttpServletResponse response, String storeName) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		String downLoadPath = ctxPath + "/file/" + storeName;
		String string = new String(storeName.getBytes("GB2312"), "8859_1");
		response.addHeader("Content-Disposition", "attachment;filename=" + string);
		response.setContentType("application/msword");
		FileInputStream in = new FileInputStream(new File(downLoadPath));
		OutputStream out = response.getOutputStream();
		byte[] b = new byte[512];
		while ((in.read(b)) != -1) {
			out.write(b);
		}
		out.flush();
		in.close();
		out.close();
	}
	
	@RequestMapping("/devExcel")
	@ResponseBody
	public void devExcel(HttpServletRequest request, HttpServletResponse response, String storeName) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		String downLoadPath = ctxPath + "/file/" + storeName;
		response.setContentType("application/vnd.ms-excel");
		
		FileInputStream in = new FileInputStream(new File(downLoadPath));
		OutputStream out = response.getOutputStream();
		byte[] b = new byte[512];
		while ((in.read(b)) != -1) {
			out.write(b);
		}
		out.flush();
		in.close();
		out.close();
	}
	
    /** 
	 * @param response
	 * @param wb excel生成的Workbook （根据业务创建Workbook）
	 * @throws IOException
	 */
	@RequestMapping("/devExcel1")
	public void writToAjax(HttpServletResponse response, String storeName) throws IOException {
		try {
			InputStream input = new FileInputStream("C://Users/Administrator/Desktop/"+storeName);
			HSSFWorkbook wb = new HSSFWorkbook(input);
			ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
					DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
			ethc.setOutputColumnHeaders(false);
			ethc.setOutputRowNumbers(false);
			ethc.processWorkbook(wb);

			Document htmlDocument = ethc.getDocument();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			DOMSource domSource = new DOMSource(htmlDocument);
			StreamResult streamResult = new StreamResult(out);

			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.setOutputProperty(OutputKeys.METHOD, "html");
			serializer.transform(domSource, streamResult);
			out.close();

			String htmlStr = new String(out.toByteArray(), "UTF-8");

			htmlStr = htmlStr.replace("<h2>Sheet1</h2>", "").replace("<h2>Sheet2</h2>", "")
					.replace("<h2>Sheet3</h2>", "").replace("<h2>Sheet4</h2>", "").replace("<h2>Sheet5</h2>", "");
			response.setContentType("text/html;charset=utf-8");
			PrintWriter pw = response.getWriter();
			pw.print(htmlStr);
			pw.flush();
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/devWord1")
	@ResponseBody
	public void devWord1(HttpServletRequest request, HttpServletResponse response, String storeName) throws Exception {

		
  
                // 1) 加载word文档生成 XWPFDocument对象  
            	InputStream in = new FileInputStream("C://Users/Administrator/Desktop/"+storeName);  
                XWPFDocument document = new XWPFDocument(in);  
  
                // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)  
//                File imageFolderFile = new File("C://Users/Administrator/Desktop/");  
//                File imageFolderFile = new File("/file");  
                File imageFolderFile = new File("F:/ssh/work/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Util/");  
//                XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));  
                XHTMLOptions options = XHTMLOptions.create();  
                options.setExtractor(new FileImageExtractor(imageFolderFile));  
                options.setIgnoreStylesIfUnused(false);  
                options.setFragment(true);  
                  
                // 3) 将 XWPFDocument转换成XHTML  
                OutputStream out = response.getOutputStream();
                response.setContentType("text/html;charset=utf-8");
                XHTMLConverter.getInstance().convert(document, out, options);
				
//                PrintWriter pw = response.getWriter();
//				pw.print(document);
//				pw.flush();
//				pw.close();
                in.close();
				out.close();
	}
}
